#include <iostream>
#include <queue>
#include <map>
#include <vector>
using namespace std;

//比较规则 比频率
struct cmp{
    bool operator()(pair<int, int> p1, pair<int, int> p2){
        return p1.second > p2.second;
    }
};
vector<int> topKFrequent(int nums[], int len, int k){
    //小顶堆
    priority_queue<pair<int, int>, vector<pair<int, int>>, cmp> minHeap;
    vector<int> res;
    map<int, int> numToFrequent;
    for(int i = 0; i < len; i++){
        if(numToFrequent.count(nums[i])){
            numToFrequent[nums[i]]++;
        }else{
            numToFrequent[nums[i]] = 1;
        }
    }

    for(auto it = numToFrequent.begin(); it != numToFrequent.end(); it++){
        if(minHeap.size() < k){
            minHeap.push(*it);
        }else if(it->second > minHeap.top().second){
            minHeap.pop();
            minHeap.push(*it);
        }
    }
    while(!minHeap.empty()){
        res.push_back(minHeap.top().first);
        minHeap.pop();
    }

    return res;
}
int main(){
    int nums[] = {1, 2, 2, 1, 3, 1};
    int k = 2;
    vector<int> res = topKFrequent(nums, 6, k);

    for(int i = 0; i < res.size(); i++){
        cout<<res[i]<<endl;
    }
    return 0;
}